import asyncio
import time


# 水果生产方式
class Fruit:
    def __init__(self, name):
        self.name = name
    
    def __repr__(self):
        return self.name

    @classmethod
    async def makeone(cls, name, *args, **kwargs):
        await asyncio.sleep(1)
        shelf[name].append(cls(name))

# 下订商品
async def ask_for(n, name):
    count = 0
    while count < n:
        if len(shelf[name]) == 0:
            await Fruit.makeone(name) 
            yield shelf[name].pop()
        else:
            yield shelf[name].pop()
        count += 1

async def buy(n, name):
    async for p in ask_for(n, name):
        mybucket.append(p)
        print(f'Got {p.name} {id(p)}')

# 水果货架
shelf = {
    "apple": [],
    "banana": [],
}

Fruit.makeone("apple")

# 口袋
mybucket = []


def main():
    task1 = asyncio.ensure_future(buy(5, "apple"))
    task2 = asyncio.ensure_future(buy(10, "banana"))
    tasks = [task1, task2]
    loop = asyncio.get_event_loop()
    res = loop.run_until_complete(asyncio.gather(*tasks))
    print(res)
    print(len(res))
    print(mybucket)
    loop.close()

if __name__ == '__main__':
    start_time = time.time()
    main()
    print(f"耗时{time.time()-start_time}s")